from . import news_bp
from flask import g
from  info.utits.common import user_login_data
from flask import render_template,request
from flask import current_app,jsonify
from info import constants
from info.models import News,User,Comment,CommentLike
from info.utits.response_code import RET
from flask  import session
from flask import request
from info import constants,db


@news_bp.route('/comment_like',methods=['POST'])
@user_login_data
def comment_like():
    """
    获取参数
        点击动作的获取
        评论id的获取
    校验参数
        飞控判断
    逻辑处理
        判断是否点过赞。点过就减值
        没有点过赞就减

    返回
        返回值
    :return:
    """
    params_dict =request.json
    comment_id = params_dict.get("comment_id")
    action = params_dict.get("action")
    user = g.user

    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.PARAMERR,errmsg="用户未登录")
    if action not in ["add","remove"]:
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询评论异常")
    if not comment:
        return jsonify(errno=RET.DBERR,errmsg="评论不存在")

    # 添加点赞
    if user:
        if action == "add":
            try:
                commentlike = CommentLike.query.filter(CommentLike.comment_id == comment_id,CommentLike.user_id == user.id).first()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg="查询点子啊评论模型异常")

            if not commentlike:
                commentlike_obj = CommentLike()
                commentlike_obj.user_id = user.id
                commentlike_obj.comment_id =comment_id
                db.session.add(commentlike_obj)
                Comment.like_count+=1
        # 删除点赞
    else:
            try:
                commentlike=CommentLike.query.filter(CommentLike.comment_id ==comment_id,CommentLike.user_id == user.id).first()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg="评论模型查询异常")
            if commentlike:
                db.session.delete(commentlike)
                Comment.like_count -=1
    try:
        db.session.commit()

    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno =RET.DBERR,errmsg="保存评论点赞模型异常")
    # 返回值
    return jsonify(errno=RET.OK,errmsg="OK")
@news_bp.route('/news_comment',methods=['POST'])
@user_login_data
def news_comment():
    '''
    获取参数
        获取新闻id，用户id，子评论id,父评论id
    校验参数
        非空判断
    逻辑处理

        查询出当前新闻所属的评论
    返回值
    :return:
    '''
    # 获取用户参数，以及评论信息
    params_dict=request.json
    comment_str=params_dict.get("comment")
    news_id=params_dict.get("news_id")
    parent_id =params_dict.get("parent_id")

    # 获取用户
    user = g.user
    # 飞控判断
    if not [news_id,comment_str]:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    if not user:
        # 用户登录判断
        return jsonify(errno=RET.PARAMERR,errmsg="用户没有登录")
    try:
        # 查询出新闻的id下的新闻
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="没有查询到新闻")
    if not news:
        # 判断新闻是否存在
        return jsonify(errno=RET.NODATA,errmsg="新闻不存在")
    # parent_id 判断有没有值，如果有值就是自评论
    # 吧用户数据添加条数据库中
    comment_obj = Comment()
    comment_obj.user_id =user.id
    comment_obj.news_id = news_id
    comment_obj.content = comment_str
    if parent_id:
        comment_obj.parent_id = parent_id
        # 提交数据
    try:
        db.session.add(comment_obj)
        db.session.commit()
    except Exception as e :
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="数据保存异常")
    data = comment_obj.to_dict()
    return jsonify(errno=RET.OK,errmsg="评论成功",data=data)

# 点击收藏
@news_bp.route('/news_collect',methods=['POST'])
@user_login_data
def news_collect():
    '''
    获取参数
        获取新闻ID,点击事件
    校验参数
        非空判断
    逻辑处理
        判断新闻的是否是收藏状态，是的，就取消，否则就收藏
    返回参数
        返回状态吗

    :return:
    '''

    # 获取当前用户
    user=g.user
    param=request.json
    news_id=param.get('news_id')
    action=param.get("action")

    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")

    if not all([action,news_id]):
        return jsonify(errno=RET.SESSIONERR,errmsg="参数不足")

    if not action in ['collect','cancel_collect']:
        return jsonify(errno=RET.SESSIONERR,errmsg="参数内容错误")

    try:
        news = News.query.get('news_id')
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.NODATA,errmsg="没有该新闻")

    if action == "collect":
        # 收藏
        user.collection_news.append(news)
    if action =="cancel_collect":
        user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        jsonify(errno=RET.OK,errmsg="保存新闻数据到收藏列表异常")
    return jsonify(errno=RET.OK,errmsg="保存到新闻列表成功")

@news_bp.route('/<int:news_id>')
@user_login_data
def get_detail_news_id(news_id):
#     # -----------用户数据查询-----------
#     user_id =session.get("user_id")
#     user = None # type:User
#     if user_id:
#         try:
#             user=User.query.get(user_id)
#         except Exception as e:
#             current_app.logger.error(e)
    user=g.user
            # return jsonify(errno=RET.DBERR,errmsg="查询用户对象异常")
    # -----------点击排行新闻数据查询-------------
    """
    逻辑处理
        查询出新闻对象数据
    返回值
        解码,返回
    """
    try:
        news_rank_list=News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询点击排行数据异常")
    news_rank_dict_list=[]


    for news_obj in news_rank_list if news_rank_list else []:
        news_dict=news_obj.to_dict()
        news_rank_dict_list.append(news_dict)




    # ---------新闻详情数据查询---------

    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        jsonify(errno=RET.DBERR,errmsg="新闻详情页查询异常")

    news_dict = news.to_dict()



# ------------------查询当前用户是否收藏该新闻
    is_collected=False
    if user:
        if news in user.collection_news:
            is_collected=True

    try:
        comments=Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询评论对象异常")


    comment_id_list = [comment.id for comment in comments]
    try:
        commentlike_model_list = CommentLike.query.filter(CommentLike.comment_id.in_(comment_id_list),
                                                          CommentLike.user_id == user.id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询异常")
    commentlike_dict_list = [commentlike_model.comment_id for commentlike_model in commentlike_model_list]

    comment_dict_list=[]
    for comment in comments if comments else []:

            comment_dict =comment.to_dict()
            comment_dict["is_like"] =False
            if comment.id in commentlike_dict_list:
                comment_dict["is_like"] =True
            comment_dict_list.append(comment_dict)



    data = {

        "user_info":user.to_dict() if user else None,
        "news_rank_list":news_rank_dict_list,
        "news":news_dict,
        "is_collected":is_collected,
        "comments":comment_dict_list
    }
    return render_template("news/detail.html",data=data)

